﻿using Surf.GrpcInvoker.Demo.Core.CallHandlers;
using Surf.GrpcInvoker.Demo.Core.Interceptors;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Surf.GrpcInvoker.Demo.Core
{
    /// <summary>服务端的 服务定义器，是服务端方法名 与 方法调用器 的字典</summary>
    public class ServerServiceDefinition
    {
        readonly ReadOnlyDictionary<string, IServerCallHandler> _callHandlers;

        internal ServerServiceDefinition(Dictionary<string, IServerCallHandler> callHandlers)
        {
            _callHandlers = new ReadOnlyDictionary<string, IServerCallHandler>(callHandlers);
        }

        internal IDictionary<string, IServerCallHandler> CallHandlers => _callHandlers;

        // 实用 拦截器 重新封装
        public ServerServiceDefinition Intercept(Interceptor interceptor)
        {
            return new ServerServiceDefinition(CallHandlers.ToDictionary(x => x.Key, x => x.Value.Intercept(interceptor)));
        }

        /// <summary>创建 服务定义器的 构建器，是 服务定义 增加 方法调用器 的扩展构建器</summary>
        /// <remarks>（构建器应是临时的，构建完成后就可不需要了的）</remarks>
        public static Builder CreateBuilder()
        {
            return new Builder();
        }

        /// <summary>服务定义构建器</summary>
        public class Builder
        {
            readonly Dictionary<string, IServerCallHandler> callHandlers = new Dictionary<string, IServerCallHandler>();

            public Builder() { }

            public Builder AddMethod<TRequest, TResponse>(Method<TRequest, TResponse> method, ServerMethod<TRequest, TResponse> handler) where TRequest : class where TResponse : class
            {
                var callHandler = new ServerCallHandler<TRequest, TResponse>(method, handler);
                callHandlers.Add(method.FullName, callHandler);
                return this;
            }

            /// <summary>构建 服务定义器</summary>
            public ServerServiceDefinition Build()
            {
                return new ServerServiceDefinition(callHandlers);
            }
        }
    }
}
